package org.mspring.mlog.dao.impl;

import org.mspring.mlog.dao.PostDao;
import org.mspring.mlog.entity.Post;
import org.mspring.platform.dao.Order;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Gao Youbo
 * @since 2014-01-11
 */
@Repository
public class PostDaoImpl extends GenericDao<Post, Long> implements PostDao {

    @Override
    public void deleteByStatus(String status) {
        super.executeUpdate("delete Post post where post.status = ?", status);
    }

    @Override
    public int updateStatus(long id, String status) {
        return super.executeUpdate("update Post post set post.status = ? where post.id = ?", status, id);
    }

    @Override
    public int updateViews() {
        return super.executeUpdate("update Post p set p.views = (select sum(c.count) from Count c where c.key1 = ? and c.key2 = ? and c.key3 = p.id)", "post", "click");
    }

    @Override
    public int updateReplys() {
        return super.executeUpdate("update Post p set p.replys = (select count(*) from Comment c where c.post.id = p.id)");
    }

    @Override
    public Page<Post> listByCatalog(Page<Post> page, long catalog) {
        if (page == null) {
            page = new Page<>();
        }
        if (page.getOrder() == null || page.getOrder().isEmpty()) {
            page.addOrder("postCatalog.PK.post.id", Order.OrderType.DESC);
        }
        listPage("select postCatalog.PK.post from PostCatalog postCatalog where postCatalog.PK.catalog.id = ? and postCatalog.PK.post.status = ? order by postCatalog.PK.post.isTop desc, postCatalog.PK.post.id desc", page, catalog,
                Post.Status.PUBLISH);
        return page;
    }

    @Override
    public Page<Post> listByTag(Page<Post> page, long tag) {
        if (page == null) {
            page = new Page<>();
        }
        if (page.getOrder() == null || page.getOrder().isEmpty()) {
            page.addOrder("postTag.PK.post.id", Order.OrderType.DESC);
        }
        listPage("select postTag.PK.post from PostTag postTag where postTag.PK.tag.id = ? and postTag.PK.post.status = ? order by postTag.PK.post.isTop desc, postTag.PK.post.id desc", page, new Object[] { tag, Post.Status.PUBLISH });
        return page;
    }

    @Override
    public long countPost() {
        return getHibernateTemplate().count("select count(*) from Post post where post.status = ?", Post.Status.PUBLISH);
    }

}
